package com.asia5b.a5mall.order.activity

import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.dialog.SelectBaseDialog
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.event.OrderAfterSaleEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderAfterSaleActivityVM
import com.asia5b.a5mall.middleware.model.order.OrderAfterSaleDetailModel
import com.asia5b.a5mall.middleware.model.bean.SelectText
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.KeyboardStateObserver
import com.asia5b.a5mall.middleware.utils.getEventBus
import com.asia5b.a5mall.middleware.utils.pop
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.OrderAfterSaleGoodsAdapter
import com.asia5b.a5mall.order.databinding.ActivityOrderaftersaleBinding
import kotlinx.android.synthetic.main.activity_orderaftersale.*
import org.greenrobot.eventbus.EventBus

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   订单售后页面,todo 对单个商品退货退款
 */
@Route(path = ActCons.OrderAfterSaleActivity)
class OrderAfterSaleActivity : SimpleActivity<OrderAfterSaleActivityVM, ActivityOrderaftersaleBinding>() {
    override val viewModelClazz: Class<OrderAfterSaleActivityVM>
        get() = OrderAfterSaleActivityVM::class.java

    override fun getDataBinding(): ActivityOrderaftersaleBinding {
        orderSn = intent.getStringExtra("orderSn")!!
        if (intent.hasExtra("skuId")) {
            skuId = intent.getIntExtra("skuId", 0)
        }
        return ActivityOrderaftersaleBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    var orderSn: String = ""
    var skuId: Int = 0//确认收货后针对单个商品的售后
    var goodsModel: AbsGoodsModel? = null//确认收货后针对单个商品的售后

    var orderAfterSaleDetailModel: OrderAfterSaleDetailModel? = null//对订单售后的详情

    //实际支付货币符号
    var actual_currency_short = ""

    val mDatas = arrayListOf<AbsGoodsModel>()
    val mAdapter by lazy { OrderAfterSaleGoodsAdapter(mDatas) }
    val mRecyclerView by lazy { rv_orderaftersale }

    //退款退货方式
    lateinit var selectTextServiceType: SelectText
    val selectTextList by lazy {
        arrayListOf<SelectText>().apply {
            var index = 0
            add(SelectText.newInstance(getString(R.string.申请退款), index++))
            add(SelectText.newInstance(getString(R.string.申请退货), index++))
        }
    }

    //退款原因
    lateinit var selectReason: SelectText
    val selectReasonList by lazy {
        arrayListOf<SelectText>().apply {
            var index = 0
            add(SelectText.newInstance(getString(R.string.商品质量有问题), index++))
            add(SelectText.newInstance(getString(R.string.收到商品与描述不符), index++))
            add(SelectText.newInstance(getString(R.string.不喜欢_不想要), index++))
            add(SelectText.newInstance(getString(R.string.发票问题), index++))
            add(SelectText.newInstance(getString(R.string.空包裹), index++))
            add(SelectText.newInstance(getString(R.string.快递无记录), index++))
            add(SelectText.newInstance(getString(R.string.快递一直没有收到), index++))
            add(SelectText.newInstance(getString(R.string.买错_不想要), index++))
            add(SelectText.newInstance(getString(R.string.其他), index++))
            add(SelectText.newInstance(getString(R.string.未按照时间发货), index++))
        }
    }

    val keyboardStateObserver by lazy { KeyboardStateObserver.getKeyboardStateObserver(mActivity) }

    override fun initView() {
        selectTextServiceType = selectTextList[0]
        setReturnServiceTypeView()
        selectReason = selectReasonList[0]
        setReasonView()
        plus_orderaftersale.qty = 0
        plus_orderaftersale.setMinQty(0)
        plus_orderaftersale.setMaxQty(0)



        mRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = mAdapter
        }


    }


    /**
     * 显示选择框
     */
    fun showSelectDialog(title: String) {
        when (title) {
            getString(R.string.服务类型) -> {//服务类型
                SelectBaseDialog(mActivity).apply {
                    this.title = title
                    mDatas.addAll(selectTextList)
                    this.selectText = selectTextServiceType
                    this.setSureClick<SelectText> {
                        selectTextServiceType = it
                        setReturnServiceTypeView()
                    }
                }.show()
            }
            getString(R.string.退款原因) -> {
                SelectBaseDialog(mActivity).apply {
                    this.title = title
                    mDatas.addAll(selectReasonList)
                    this.selectText = selectReason
                    this.setSureClick<SelectText> {
                        selectReason = it
                        setReasonView()
                    }
                }.show()
            }
        }
    }

    /**
     * 设置退款类型
     */
    fun setReturnServiceTypeView() {
        if (selectTextServiceType.getSelectId() == 0) {
            tv_orderaftersale_returntype.setText(R.string.退款)

            ll_orderaftersale_returnnum.visibility = View.GONE
        } else {
            tv_orderaftersale_returntype.setText(R.string.退货)

            ll_orderaftersale_returnnum.visibility = View.VISIBLE
        }
        setReturnPriceView()
    }

    fun setReasonView() {
        tv_orderaftersale_reason.text = selectReason.getText()
    }

    /**
     * 设置退款价格
     */
    fun setReturnPriceView() {
        if (goodsModel != null) {//确认收货后针对单个商品的售后
            if (selectTextServiceType.getSelectId() == 0) {//退款
                tv_orderaftersale_price.text = String.format("%s %.2f", actual_currency_short, (goodsModel!!.absGoodsSetNum * goodsModel!!.absGoodsReturnPrice))
            } else {//退货
                //退款价格 套数*单套价格
                tv_orderaftersale_price.text = String.format("%s %.2f", actual_currency_short, (plus_orderaftersale.qty * goodsModel!!.absGoodsReturnPrice))
            }
        } else {//付款后,未确认收货对订单的售后
            tv_orderaftersale_price.text = String.format("%s %.2f", actual_currency_short, orderAfterSaleDetailModel?.return_money
                    ?: 0.0)
        }
    }


    override fun initEvent() {
        bt_orderaftersale_submit.setOnClickListener {
            submit()
        }
        if (skuId > 0) {//确认收货后针对单个商品的售后
            ll_orderaftersale_returntype.setOnClickListener {
                showSelectDialog(getString(R.string.服务类型))
            }
        } else {//付款后,未确认收货对订单的售后
            ll_orderaftersale_returntype.isEnabled = false
            tv_orderaftersale_returntype_title.setTextColor(ContextCompat.getColor(mActivity, R.color.common_text_gray))
            tv_orderaftersale_returntype.setTextColor(ContextCompat.getColor(mActivity, R.color.common_text_gray))
        }
        ll_orderaftersale_reason.setOnClickListener {
            showSelectDialog(getString(R.string.退款原因))
        }
        plus_orderaftersale.setListener {
            setReturnPriceView()
        }
        keyboardStateObserver.setKeyboardVisibilityListener(object : KeyboardStateObserver.OnKeyboardVisibilityListener {
            override fun onKeyboardShow() {
            }

            override fun onKeyboardHide() {
                plus_orderaftersale.hideKeyboard()
            }

        })
    }

    override fun initData() {
        mViewModel.getOrderAftersaleDetail(orderSn, skuId)
    }

    fun submit() {

        //退款接口参数
        val map = HashMap<String, Any>()
        map["order_sn"] = orderSn

        map["refund_reason"] = selectReason.getText()
        map["customer_remark"] = et_orderaftersale_desc.text.toString()

        if (skuId > 0) {//确认收货后针对单个商品的售后
            map["sku_id"] = skuId

            if (selectTextServiceType.getSelectId() == 0) {//退款
                map["return_num"] = goodsModel!!.absGoodsSetNum
                map["return_money"] = "${goodsModel!!.absGoodsSetNum * goodsModel!!.absGoodsReturnPrice}"
                mViewModel.commitMoney(map)
            } else {//退货
                map["return_num"] = plus_orderaftersale.qty
                map["return_money"] = "${plus_orderaftersale.qty * goodsModel!!.absGoodsReturnPrice}"
                mViewModel.commitGoods(map)
            }
        } else {
            map["return_money"] = "${orderAfterSaleDetailModel!!.return_money}"
            mViewModel.cancelPaidOrder(map)
        }


    }


     fun getOrderAftersaleDetailResult(result: OrderAfterSaleDetailModel) {
        orderAfterSaleDetailModel = result
        actual_currency_short = result.order?.actual_currency_short ?: ""
        if (skuId > 0) {//确认收货后针对单个商品的售后
            goodsModel = result.sku_list?.getOrNull(0)?.run {
                mDatas.clear()
                mDatas.add(this)
                mAdapter.notifyDataSetChanged()
                this
            }

            goodsModel!!.run {
                plus_orderaftersale.qty = this.absGoodsSetNum
                plus_orderaftersale.setMinQty(1)
                plus_orderaftersale.setMaxQty(this.absGoodsSetNum)
                plus_orderaftersale.openEditText()
                if (this.absGoodsSetNum == 1) {
                    plus_orderaftersale.closeEditText()
                }
            }
        } else {//付款后,未确认收货对订单的售后
            result.sku_list?.run {
                mDatas.clear()
                mDatas.addAll(this)
                mAdapter.notifyDataSetChanged()
            }
        }

        setReturnPriceView()
        bt_orderaftersale_submit.isEnabled = (orderAfterSaleDetailModel != null)
    }

  override  fun startObserver() {
        mViewModel.getOrderAftersaleDetailResultLiveData.observe(this, Observer {
            getOrderAftersaleDetailResult(it)
        })
        mViewModel.commitMoneyResultLiveData.observe(this, Observer {
            commitMoneyResult()
        })
        mViewModel.commitGoodsResultLiveData.observe(this, Observer {
            commitGoodsResult()
        })
    }

    fun commitMoneyResult() {
        getEventBus().post(OrderAfterSaleEvent())
        pop()
    }

    fun commitGoodsResult() {
        getEventBus().post(OrderAfterSaleEvent())
        pop()
    }

    override fun onDestroy() {
        keyboardStateObserver.destory()
        super.onDestroy()
    }
}